<template>
    <el-form :model="form" label-width="120px" style="max-width: 800px">
        <!-- 物料信息 -->
        <el-form-item label="物料名称" prop="itemName">
            <el-select v-model="form.itemName" placeholder="请选择物料" clearable @change="handleMaterialChange"
                style="width: 100%">
                <el-option label="瓶子" value="瓶子" />
                <el-option label="铁罐" value="铁罐" />
                <el-option label="纸箱" value="纸箱" />
            </el-select>
        </el-form-item>

        <el-form-item label="物料规格" prop="itemspecification">
            <el-input v-model="form.itemspecification" :disabled="!!form.itemName" placeholder="自动填充" />
        </el-form-item>

        <el-form-item label="物料类型" prop="itemType">
            <el-input v-model="form.itemType" :disabled="!!form.itemName" placeholder="自动填充" />
        </el-form-item>

        <el-form-item label="批次号" prop="lotNumber">
            <el-input v-model="form.lotNumber" :disabled="!!form.itemName" placeholder="自动填充" />
        </el-form-item>

        <!-- 日期信息 -->
        <el-form-item label="生产日期" prop="manufactureDate">
            <el-date-picker v-model="form.manufactureDate" type="date" placeholder="选择生产日期" value-format="YYYY-MM-DD"
                @change="calculateExpirationDate" style="width: 100%" />
        </el-form-item>

        <el-form-item label="有效日期" prop="expirationDate">
            <el-date-picker v-model="form.expirationDate" type="date" placeholder="自动计算" value-format="YYYY-MM-DD"
                :disabled="true" style="width: 100%" />
        </el-form-item>

        <!-- 数量信息 -->
        <el-form-item label="计划备料数量" prop="plannedQuantity">
            <el-input-number v-model="form.plannedQuantity" :min="1" :step="1" style="width: 100%" />
        </el-form-item>

        <el-form-item label="实际备料数量" prop="actualQuantity">
            <el-input-number v-model="form.actualQuantity" :min="0" :step="1" style="width: 100%" />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" placeholder="如：个、kg" />
        </el-form-item>

        <el-form-item label="
        产品名称" prop="productionOrderNumber">
            <el-select v-model="selectedPackaging" placeholder="please select your zone" @change="handlePackagingChange">
                <el-option v-for="packaging in getpackaginglist" :key="packaging.packagingPlanId" :label="packaging.productRange" :value="packaging.productRange" />
            </el-select>
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

onMounted(() => {
    getpackaging()
})

const getpackaginglist = ref([{
    packagingPlanId: 0,
    productRange: "",
}])

const selectedPackaging = ref('')

//显示生产计划
const getpackaging = () => {
    axios.get('http://localhost:5118/api/PackagingPlan/GetPackagingPlan', {
        params: {
            PageIndex: 1,
            PageSize: 1000
        }
    }).then(res => {
        getpackaginglist.value = res.data.data.list
        console.log(getpackaginglist.value)
    })
}

// 物料配置数据
const materialConfig = {
    '瓶子': {
        spec: '250/330ml',
        type: '玻璃',
        lot: 'LOT2207A-3-Glass'
    },
    '铁罐': {
        spec: '9/12ml',
        type: '铁制品',
        lot: 'LOT-2207A-3-Cans'
    },
    '纸箱': {
        spec: '530*290*370mm',
        type: '纸制品',
        lot: 'LOT-2207A-3-Paper'
    }
}

// 表单数据
const form = reactive({
    itemName: '',
    itemspecification: '',
    itemType: '',
    lotNumber: '',
    manufactureDate: '',
    expirationDate: '',
    plannedQuantity: 0,
    actualQuantity: 0,
    unit: '',
    productionOrderNumber: ''
})

// 物料选择变化处理
const handleMaterialChange = (value: string) => {
    if (value && materialConfig[value]) {
        const { spec, type, lot } = materialConfig[value]
        form.itemspecification = spec
        form.itemType = type
        form.lotNumber = lot
    } else {
        form.itemspecification = ''
        form.itemType = ''
        form.lotNumber = ''
    }
}

// 计算有效期（生产日期+1个月）
const calculateExpirationDate = (date: string) => {
    if (!date) {
        form.expirationDate = ''
        return
    }

    const dateObj = new Date(date)
    const newDate = new Date(dateObj)

    // 处理月份溢出（如12月+1=13→次年1月）
    newDate.setMonth(dateObj.getMonth() + 1)

    // 处理日期溢出（如1月31日+1个月→2月28/29日）
    if (newDate.getDate() !== dateObj.getDate()) {
        newDate.setDate(0) // 设置为上个月的最后一天
    }

    // 格式化为YYYY-MM-DD
    form.expirationDate = newDate.toISOString().split('T')[0]
}

// 提交表单
const submitForm = async () => {
    try {
        const response = await axios.post('http://localhost:5293/api/MaterialPreparation/Handle', {
            itemName: form.itemName,
            itemspecification: form.itemspecification,
            itemType: form.itemType,
            lotNumber: form.lotNumber,
            manufactureDate: form.manufactureDate,
            expirationDate: form.expirationDate,
            plannedQuantity: form.plannedQuantity,
            actualQuantity: form.actualQuantity,
            unit: form.unit,
            productionOrderNumber: form.productionOrderNumber
        })
        if (response.data.code === 200) {
            ElMessage.success('提交成功')
            resetForm()
        } else {
            ElMessage.error(response.data && response.data.message || '提交失败')
        }
    } catch (error) {
        ElMessage.error(`请求错误: ${error}`)
    }
}

// 重置表单
const resetForm = () => {
    Object.assign(form, {
        itemName: '',
        itemspecification: '',
        itemType: '',
        lotNumber: '',
        manufactureDate: '',
        expirationDate: '',
        plannedQuantity: 0,
        actualQuantity: 0,
        unit: '',
        productionOrderNumber: ''
    })
    selectedPackaging.value = ''
}

// 处理生产订单号下拉框选择事件
const handlePackagingChange = (value) => {
    form.productionOrderNumber = value
}
</script>

<style scoped>
/* 禁用状态样式 */
.el-input.is-disabled :deep(.el-input__inner),
.el-input-number.is-disabled :deep(.el-input__inner) {
    color: #606266;
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    cursor: not-allowed;
}
</style>    